package xin.clips.system.service.impl;


import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.transaction.annotation.Transactional;
import xin.clips.common.core.domain.AjaxResult;
import xin.clips.common.core.domain.entity.SysUser;
import xin.clips.common.enums.gy.InnerMessageStatusEnum;
import xin.clips.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.clips.common.core.text.Convert;
import xin.clips.system.domain.gy.GyDeviceMgt;
import xin.clips.system.domain.gy.GyInnerMessage;
import xin.clips.system.domain.gy.GyWorkOrder;
import xin.clips.system.dto.NameValueDataDTO;
import xin.clips.system.mapper.gy.GyWorkOrderMapper;
import xin.clips.system.service.gy.IGyDeviceMgtService;
import xin.clips.system.service.gy.IGyInnerMessageService;
import xin.clips.system.service.gy.IGyWorkOrderService;

/**
 * 工单信息Service业务层处理
 *
 * @author clips
 * @date 2023-03-10
 */
@Service
public class GyWorkOrderServiceImpl implements IGyWorkOrderService {
    @Autowired
    private GyWorkOrderMapper gyWorkOrderMapper;

    @Autowired
    private IGyInnerMessageService innerMessageService;

    @Autowired
    private IGyDeviceMgtService deviceMgtService;

    /**
     * 查询工单信息
     *
     * @param workId 工单信息主键
     * @return 工单信息
     */
    @Override
    public GyWorkOrder selectGyWorkOrderByWorkId(Long workId) {
        return gyWorkOrderMapper.selectGyWorkOrderByWorkId(workId);
    }

    /**
     * 查询工单信息列表
     *
     * @param gyWorkOrder 工单信息
     * @return 工单信息
     */
    @Override
    public List<GyWorkOrder> selectGyWorkOrderList(GyWorkOrder gyWorkOrder) {
        return gyWorkOrderMapper.selectGyWorkOrderList(gyWorkOrder);
    }

    /**
     * 新增工单信息
     *
     * @param gyWorkOrder 工单信息
     * @return 结果
     */

    @Override
    @Transactional
    public AjaxResult insertGyWorkOrder(GyWorkOrder gyWorkOrder) {
        if (!this.checkWorkOrderNameUnique(gyWorkOrder)) {
            return AjaxResult.error("新增工单失败，工单名称存在重复!");
        }
        GyDeviceMgt deviceMgt = new GyDeviceMgt();
        deviceMgt.setDeviceType(gyWorkOrder.getDeviceType());
        deviceMgt.setUser(new SysUser());
        List<GyDeviceMgt> list = deviceMgtService.selectGyDeviceMgtList(deviceMgt);
        if (CollUtil.isEmpty(list)) {
            return AjaxResult.error("新增工单失败，请联系管理员至设备消息绑定页面配置设备处理责任人!");
        }
        gyWorkOrder.setCreateTime(DateUtils.getNowDate());
        Integer maxId= gyWorkOrderMapper.selectMaxId();
        if(maxId==null){
            maxId=0;
        }
        gyWorkOrder.setEventNumber(ProducerNumUtil.getId("g", ( maxId + 1)));
        //新增完成工单后，进行站内信绑定
        GyInnerMessage msg = null;
        List<GyInnerMessage> innerMessages = new ArrayList<>();
        Long primaryUser = 0l;
        String otherUsers = "";

        for (GyDeviceMgt mgt : list) {
            msg = new GyInnerMessage();
            msg.setAcceptUserId(mgt.getUserId());  //接受者id
            msg.setSendUserId(ShiroUtils.getUserId()); //发信者id
            msg.setCreateBy(ShiroUtils.getLoginName()); //'创建者'
            msg.setCreateTime(DateUtils.getNowDate());
            msg.setInnerMessageStatus(Integer.parseInt(InnerMessageStatusEnum.UNREAD.getCode()));
            msg.setSendTime(DateUtils.getNowDate());  //'发信时间'
            msg.setMemo( gyWorkOrder.getName() );  //'信件内容'
            otherUsers += mgt.getUserId().toString() + ",";
            if (mgt.getIsPrincipal().toString().equals("1")) {
                primaryUser = mgt.getUserId();
            }
            msg.setMessageType(gyWorkOrder.getWorkType());
            innerMessages.add(msg);
        }
        gyWorkOrder.setPrimaryUserId(primaryUser);
        if (!otherUsers.equals(""))
            gyWorkOrder.setOtherUserIds(otherUsers.substring(0, otherUsers.length() - 1));
        gyWorkOrderMapper.insertGyWorkOrder(gyWorkOrder);

        for (GyInnerMessage innerMessage : innerMessages) {
            innerMessage.setWorkOrderId(gyWorkOrder.getWorkId());
            innerMessageService.insertGyInnerMessage(innerMessage);
        }
        return AjaxResult.success();
    }

    /**
     * 检查工单名称是否唯一
     *
     * @param order
     * @return false 表示存在重复 ,true表示不存在重复
     */
    public boolean checkWorkOrderNameUnique(GyWorkOrder order) {
        Long id = StringUtils.isNull(order.getWorkId()) ? -1L : order.getWorkId();
        GyWorkOrder info = gyWorkOrderMapper.checkWorkOrderNameUnique(order.getName());
        if (ObjectUtil.isNotEmpty(info) && info.getWorkId().longValue() != id) {
            return false;
        }
        return true;
    }

    /**
     * 检查编号是否唯一
     *
     * @param order
     * @return false 表示存在重复 ,true表示不存在重复
     */
    public boolean checkWorkOrderNoUnique(GyWorkOrder order) {
        Long id = StringUtils.isNull(order.getWorkId()) ? -1L : order.getWorkId();
        GyWorkOrder info = gyWorkOrderMapper.checkWorkOrderEventNumberUnique(order.getEventNumber());
        if (ObjectUtil.isNotEmpty(info) && info.getWorkId().longValue() != id) {
            return false;
        }
        return true;
    }

    /**
     * 检查工单编号是否唯一
     *
     * @param order
     * @return false 表示存在重复 ,true表示不存在重复
     */
    public boolean checkWorkOrderEventNumberUnique(GyWorkOrder order) {
        Long id = StringUtils.isNull(order.getWorkId()) ? -1L : order.getWorkId();
        GyWorkOrder info = gyWorkOrderMapper.checkWorkOrderEventNumberUnique(order.getEventNumber());
        if (ObjectUtil.isNotEmpty(info) && info.getWorkId().longValue() != id) {
            return false;
        }
        return true;
    }

    /**
     * 修改工单信息
     *
     * @param gyWorkOrder 工单信息
     * @return 结果
     */
    @Override
    public int updateGyWorkOrder(GyWorkOrder gyWorkOrder) {
        gyWorkOrder.setUpdateTime(DateUtils.getNowDate());
        return gyWorkOrderMapper.updateGyWorkOrder(gyWorkOrder);
    }

    /**
     * 批量删除工单信息
     *
     * @param workIds 需要删除的工单信息主键
     * @return 结果
     */
    @Override
    public int deleteGyWorkOrderByWorkIds(String workIds) {
        return gyWorkOrderMapper.deleteGyWorkOrderByWorkIds(Convert.toStrArray(workIds));
    }

    /**
     * 删除工单信息信息
     *
     * @param workId 工单信息主键
     * @return 结果
     */
    @Override
    public int deleteGyWorkOrderByWorkId(Long workId) {
        return gyWorkOrderMapper.deleteGyWorkOrderByWorkId(workId);
    }

    /**
     * 查询我的工单信息列表
     *
     * @param gyWorkOrder 工单信息
     * @return 工单信息集合
     */
    public List<GyWorkOrder> selectMyWorkOrderList(GyWorkOrder gyWorkOrder) {
        return gyWorkOrderMapper.selectMyWorkOrderList(gyWorkOrder);
    }


    /**
     * 工单审核通过
     *
     * @param gyWorkOrder 工单信息
     * @return 结果
     */
    @Transactional
    public int pass(GyWorkOrder gyWorkOrder) {
        GyWorkOrder dbOrder = this.selectGyWorkOrderByWorkId(gyWorkOrder.getWorkId());
        dbOrder.setWorkStatus(3);
        dbOrder.setMemo(gyWorkOrder.getMemo());
        dbOrder.setAuditUserId(ShiroUtils.getUserId());
        this.updateGyWorkOrder(dbOrder);
        GyInnerMessage msg = new GyInnerMessage();
        msg.setAcceptUserId(dbOrder.getProcessUserId());  //处理者id
        msg.setSendUserId(ShiroUtils.getUserId()); //发信者id
        msg.setCreateBy(ShiroUtils.getLoginName()); //'创建者'
        msg.setCreateTime(DateUtils.getNowDate());
        msg.setInnerMessageStatus(0);
        msg.setSendTime(DateUtils.getNowDate());  //'发信时间'


        msg.setMemo(dbOrder.getName() + "已审核通过");  //'信件内容'

        return innerMessageService.insertGyInnerMessage(msg);
    }

    /**
     * 工单不通过
     *
     * @param gyWorkOrder 工单信息
     * @return 结果
     */
    @Transactional
    public int notpass(GyWorkOrder gyWorkOrder) {
        GyWorkOrder dbOrder = this.selectGyWorkOrderByWorkId(gyWorkOrder.getWorkId());
        dbOrder.setWorkStatus(4);
        dbOrder.setMemo(gyWorkOrder.getMemo());
        dbOrder.setAuditUserId(ShiroUtils.getUserId());
        this.updateGyWorkOrder(dbOrder);
        GyInnerMessage msg = new GyInnerMessage();
        msg.setAcceptUserId(dbOrder.getProcessUserId());  //处理者id
        msg.setSendUserId(ShiroUtils.getUserId()); //发信者id
        msg.setCreateBy(ShiroUtils.getLoginName()); //'创建者'
        msg.setCreateTime(DateUtils.getNowDate());
        msg.setInnerMessageStatus(0);
        msg.setSendTime(DateUtils.getNowDate());  //'发信时间'
        msg.setMemo("您工单内容为\"" + dbOrder.getName() + "\"已被拒绝，拒绝原因：" + gyWorkOrder.getMemo() + "");  //'信件内容'
        return innerMessageService.insertGyInnerMessage(msg);
    }

    /**
     * 申请完成处理
     *
     * @param gyWorkOrder
     * @return
     */
    public int updateGyWorkOrderFinsh(GyWorkOrder gyWorkOrder) {
        GyWorkOrder dbWorkOrder = gyWorkOrderMapper.selectGyWorkOrderByWorkId(gyWorkOrder.getWorkId());
        dbWorkOrder.setStartTime(gyWorkOrder.getStartTime());
        dbWorkOrder.setEndTime(gyWorkOrder.getEndTime());
        dbWorkOrder.setProcessContent(gyWorkOrder.getProcessContent());
        dbWorkOrder.setFilePath(gyWorkOrder.getFilePath());
        dbWorkOrder.setWorkStatus(2);
        dbWorkOrder.setAuditTime(DateUtils.getNowDate());
        dbWorkOrder.setFileName(gyWorkOrder.getFileName());
        return gyWorkOrderMapper.updateGyWorkOrder(dbWorkOrder);
    }


    /**
     * 查询我的工单信息列表
     *
     * @param gyWorkOrder 工单信息
     * @return 工单信息集合
     */
    public List<GyWorkOrder> selectAuditWorkOrderList(GyWorkOrder gyWorkOrder) {
        return gyWorkOrderMapper.selectAuditWorkOrderList(gyWorkOrder);
    }

    /**
     * 工单状态分类统计
     *
     * @param gyWorkOrder 工单信息
     * @return 工单信息集合
     */
    public List<NameValueDataDTO> selectWorkOrderStatusTotal(GyWorkOrder gyWorkOrder) {
        return gyWorkOrderMapper.selectWorkOrderStatusTotal(gyWorkOrder);
    }


    /**
     * 查询最大的id
     *
     * @return
     */
    public Integer selectMaxId() {
        return gyWorkOrderMapper.selectMaxId();
    }

    public List<GyWorkOrder> selectWorkOrderAnalyByTime(GyWorkOrder gyWorkOrder){
        return gyWorkOrderMapper.selectWorkOrderAnalyByTime(gyWorkOrder);
    }

    /**
     * 工单状态趋势图已审核
     *
     * @param gyWorkOrder 工单信息
     * @return 工单信息集合
     */
    public List<GyWorkOrder> selectWorkOrderAuthedAnalyByTime(GyWorkOrder gyWorkOrder){
        return gyWorkOrderMapper.selectWorkOrderAuthedAnalyByTime(gyWorkOrder);
    }
}
